<?php
// app/Controller/UsersController.php
class UsersController extends AppController {
    
    var $uses = array(
       'User',
       'Message',
       'MessageReciever'
    );

    # Set the layout to use
    var $layout = 'users_layout';
    
    public function beforeFilter() {
        parent::beforeFilter();
        //$this->Security->blackHoleCallback = 'my_blackhole';
        $this->Auth->allow('login','logout','add');
    }
    
    public function my_blackhole($type) {
        return json_encode($this->blackhole($type));
	}
	
	public function login() {
	    if ($this->request->is('ajax')) {
	        $this->autoRender = false;
	        $this->autoLayout = false;
            
            if ($this->Auth->login()) {
                /** Check if account is disabled*/
                $active = $this->Auth->user('active');
                if($active == 'n'){ /** User is disable, Logout */
                    $this->Auth->logout();
                    $errors = array('code' => 1, 'mesg' => __(' Your Account is Disabled '));
    			    return json_encode($errors);
                }
                
                $errors = array('code' => 0, 'mesg' => __(' login '));
    			return json_encode($errors);
    		} 
            else {		       
    			$errors = array('code' => 1, 'mesg' => __('Invalid login Credentials'));
    			return json_encode($errors);
    		}
        }

        $this->layout = 'default';
	}
    
    
	public function logout() {
	   $this->redirect($this->Auth->logout());
	}


    public function profile(){
        $page_title = 'Profile';
        $this->set(compact('page_title'));
    }
    
    /**
	 * This function redirects the user to his appropriate page after login
	 * @name signIn
	 * @param void
	 * @return void
	 * @access public
	 */
	function action_after_login(){
		$this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
	}
    
    public function add() {
        if ($this->request->is('post')) {
            echo debug($this->request->data);
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                echo 'The user has been saved';
                $this->redirect(array('action' => 'index'));
            } else {
                echo 'The user could not be saved. Please, try again.';
            }
        }
    }
    
    /**
	 * This function update the user account Settings
	 * @name passwordChecks
	 * @param string $password_1
	 * @param string $password_2
	 * @param string $currentPassword
	 * @param string $oldPassword
	 * @return True or false or an array of errors message
	 * @access public
	 */
	function passwordChecks($password_1, $password_2, $currentPassword, $oldPassword){
		# Array containing the return data.
		$returnData = array();
		# Get the old Password provided by the user
		$currentPassword = AuthComponent::password($currentPassword);
		# Check whether the password provided by the user matches his old password
		if(strcmp($currentPassword, $oldPassword) != 0){
			$returnData['code'] = 3;
			$returnData['mesg'] =__('Wrong Old Password Provided',true);
		}
		else{ # Check whether the new supplied passwords match
			if(strcmp($password_1, $password_2) != 0){
				$returnData['code'] = 4;
				$returnData['mesg'] =__('Password do not match',true);
			}
			else{
				#Password Check Success
				$returnData['code'] = 0;
				$returnData['mesg'] =__('Success',true);
			}
		}
		return $returnData;
	}

	/**
	 * This function update the user credentials
	 * @name changeLogin
	 * @param void
	 * @return Json data
	 * @access public
	 */
	function changeLogin(){
		# return array data
		$returnData = array();
		# check whether the HTTP Request is an ajax request
		if($this->request->is('ajax')){
			# disable the rendering of the layout
			$this->autoRender = false;
			$this->autoLayout = false;
            
			# Get the data provided
			$loginName = $_POST['username'];
            $first_name = $_POST['first_name'];
            $last_name = $_POST['last_name'];
			$new_pass_1 = $_POST['password_1'];
			$new_pass_2 = $_POST['password_2'];
            $upt_id = $_POST['account_upt_id'];
			$supp_cur_pass = $_POST['old_password'];
			$resetPass = !empty($_POST['reset-pass-check']) ? true: false;

			# Get the user session data
			//$loggedUser = $this->Session->read('userSessionData');
			//$id = $loggedUser['id'];
			# Get the user data from table
			$resultData = $this->User->getUserById($upt_id);
			$old_pass = $resultData['User']['password'];

			if($resetPass){
				#Password Checkings
				$passChk = $this->passwordChecks($new_pass_1, $new_pass_2, $supp_cur_pass, $old_pass);

				if($passChk['code'] == 0){
				   
                    $this->User->id = $upt_id;
            		$data['User'] = array(
						'username' => $loginName ,
                        'first_name' => $first_name,
                        'last_name' => $last_name,
						'password' => $new_pass_1
					);
            		# save the data
            		$saveStatus = $this->User->save($data);
          
					if($saveStatus){
						$returnData['code'] = 0;
						$returnData['mesg'] =__('Account settings saved!',true);
					}
					else{
						$returnData['code'] = 1;
						$returnData['mesg'] =$this->User->invalidFields();
					}
				}
				else{
					$returnData['code'] = $passChk['code'];
					$returnData['mesg'] = $passChk['mesg'];
				}
			}
			else{
        	    $this->User->id = $upt_id;
        		$data['User'] = array(
					'username' => $loginName ,
                    'first_name' => $first_name,
                    'last_name' => $last_name,
				);
        		# save the data
        		$saveStatus = $this->User->save($data, true, array('username','first_name','last_name','modified_by','modification_date'));
      
				if($saveStatus){
					$returnData['code'] = 0;
					$returnData['mesg'] =__('Account settings saved!  Reload the page for new changes.',true);
                    //Referesh Auth data
                    $this->Session->write('Auth', $this->User->read(null, $upt_id));
				}
				else{
					$returnData['code'] = 1;
					$returnData['mesg'] =$this->User->invalidFields();
				}
			}
			echo json_encode($returnData);
		}
	}


    function always_hide(){
        if($this->request->is('ajax')){
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;

            $loggedUser = $this->Auth->user();
            $upt_id = $loggedUser['id'];

            $status = $_POST['status'];

            $this->User->id = $upt_id;
            $data['User'] = array(
                'always_hide' => $status
            );

            # save the data
            $s=$this->User->save($data, true, array('always_hide'));
            //debug($s);
            //Referesh Auth data
            $this->Session->write('Auth', $this->User->read(null, $upt_id));

        }
    }


    function messages(){

        $loggedUser = $this->Auth->user();
        $user_id = $loggedUser['id'];

        if($this->request->is('ajax')){
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;

            $action = $_POST['action'];

            switch ($action) {
                case 'add' :
                   // debug($this->request->data);
                    //exit;

                    # save the data
                    if ($this->Message->saveAll($this->request->data)) {
                        return json_encode(array('code' => 0, 'mesg' => __('Message Sent')));
                    }
                    else {
                        return json_encode(array('code' => 1, 'mesg' => __('Message Not Sent')));
                    }
                break;
                case 'load' :
                    $msg_id = $_POST['data-id'];
                    $msg_type = $_POST['msg-type'];
                    $msg_status = $_POST['msg-status'];

                    $msg = $this->Message->find('first',array(
                        'conditions'=>array('Message.id'=>$msg_id),
                        'contain'=>array('User','MessageReciever'=>array('User')),
                        'recursive'=>2,
                    ));

                    //Mark as read if it's the first time the user is accessing this message.
                    if($msg_type == 'inbox' && $msg_status == 'unread'){
                        $reciever_id = null;
                        foreach($msg['MessageReciever'] as $reciever){
                            if($reciever['user_id'] == $user_id){
                                $reciever_id = $reciever['id'];
                                break;
                            }
                        }
                        $this->MessageReciever->id = $reciever_id;
                        $data['MessageReciever'] = array(
                            'msg_status' => 'read'
                        );
                        # save the data
                        $s=$this->MessageReciever->save($data);
                    }

                    return json_encode(array('data' => $msg));

                break;
                case 'delete' :
                    $delete_id = $_POST['data-id'];
                    $msg_type = $_POST['delete-type'];
                    $delete_action = $_POST['delete-action'];
                    if($delete_action == 'trash'){
                        if($msg_type == 'inbox'){
                            $this->MessageReciever->id = $delete_id;
                            $data['MessageReciever'] = array(
                                'trash' => 'y'
                            );
                            # save the data
                            $s=$this->MessageReciever->save($data);
                        }
                        else{
                            $this->Message->id = $delete_id;
                            $data['Message'] = array(
                                'trash' => 'y'
                            );
                            # save the data
                            $s=$this->Message->save($data);
                        }
                    }
                    else{//Empty trash
                        if($msg_type == 'inbox'){
                            $this->MessageReciever->id = $delete_id;
                            $data['MessageReciever'] = array(
                                'trash' => 'y',
                                'deleted' => 'y'
                            );
                            # save the data
                            $s=$this->MessageReciever->save($data);
                        }
                        else{
                            $this->Message->id = $delete_id;
                            $data['Message'] = array(
                                'trash' => 'y',
                                'deleted' => 'y'
                            );
                            # save the data
                            $s=$this->Message->save($data);
                        }
                    }

                    if ($s) {
                        return json_encode(array('code' => 0, 'mesg' => __('Message deleted!')));
                    }
                    else {
                        return json_encode(array('code' => 1, 'mesg' => 'Cannot delete message'));
                    }

                break;
            }

        }

        $inbox = $this->MessageReciever->find('all',array(
            'conditions'=>array('MessageReciever.user_id'=>$user_id, 'MessageReciever.trash'=>'n'),
            'contain'=>array('Message'=>array('User')),
            'recursive'=>2,
            'order'=>array('MessageReciever.id'=>'desc')
        ));

        $sent = $this->Message->find('all',array(
            'conditions'=>array('Message.user_id'=>$user_id, 'Message.trash'=>'n'),
            'contain'=>array('MessageReciever'=>array('User')),
            'recursive'=>2,
            'order'=>array('Message.id'=>'desc')
        ));

        $trash = array();
        //Inbox Trash
        $inbox_trash = $this->MessageReciever->find('all',array(
            'conditions'=>array('MessageReciever.user_id'=>$user_id, 'MessageReciever.trash'=>'y','MessageReciever.deleted'=>'n'),
            'contain'=>array('User','Message'=>array('User')),
            'recursive'=>2,
            'order'=>array('MessageReciever.id'=>'desc')
        ));
       // debug($inbox_trash);
        foreach($inbox_trash as $in){
            $in['Message']['type'] = 'inbox';
            $in['MessageReciever']['User'] = $in['User'];
            $rec = $in['MessageReciever'];
            $in['MessageReciever'] = array($rec);
            unset($in['User']);
            $trash[] = $in;
        }
        $sent_trash = $this->Message->find('all',array(
            'conditions'=>array('Message.user_id'=>$user_id, 'Message.trash'=>'y','Message.deleted'=>'n'),
            'contain'=>array('User','MessageReciever'=>array('User')),
            'recursive'=>2,
            'order'=>array('Message.id'=>'desc')
        ));
        foreach($sent_trash as $st){
            $st['Message']['type'] = 'sent';
            $st['Message']['User'] = $st['User'];
            unset($st['User']);
            $trash[] = $st;
        }

        $user_list = $this->User->find('all',array(
            'conditions'=>array('User.active'=>'y', 'User.deleted'=>'n'),
            'recursive'=>-1,
            'order'=>array('User.first_name'=>'asc','User.last_name'=>'asc')
        ));
        $user_array = array();
        foreach($user_list as $usr){
            $user_array[$usr['User']['id']] = $usr['User']['first_name'].' '.$usr['User']['last_name'];
        }

        $page_title = 'Messages';
        $this->set(compact('page_title','inbox','sent','trash','user_array'));
    }

}